package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.LV_DongtaiTG_Adapter;
import com.jaya.budan.adapter.TaRen_HorizontalListViewAdapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.base.MyApplication;
import com.jaya.budan.bean.ListUser_Information;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ImageUtils;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.Circle_ImageView;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.CustomListView;
import com.jaya.budan.views.ExpandableTextView;
import com.jaya.budan.views.HorizontalListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.android.utils.Logger;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeiboMessage;

public class GeRen_Main_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back, rl_geren_main, rl_geren_main_update_message, rl_geren_main_fans;
    private LinearLayout iv_geren_main_icon, ll_geren_main_ziliao, ll_geren_main_my_photo, ll_geren_main_tr_photo;
    private String access_token, currentUploadPath;
    private HorizontalListView main_hlv;
    private int uid;
    private Circle_ImageView iv_geren_main_header;
    private ImageView iv_geren_main_cover, iv_geren_main_is_vip, iv_geren_share, fabtn_geren_main;
    private TextView tv_geren_main_name, tv_geren_main_fans_count, tv_geren_main_age, tv_geren_main_distance, tv_geren_main_xingzuo, tv_taren_main_lock,
            tv_geren_main_mude, tv_geren_main_gqzk, tv_geren_main_guxiang, tv_geren_main_work, tv_geren_main_sflb, tv_geren_main_style, tv_geren_main_tixing, tv_geren_main_style2;
    private Button btn_gerentg_tgjl, btn_gerentg_ddjl;
    private CustomListView lv_geren_main_dongtai;
    private ExpandableTextView tv_geren_main_gxqm;
    private static final int TAKE_PHOTO = 0;
    private static final int RESULT_REQUEST_CODE=2;
    private Uri photoUri;
    private User_Limit user_limit;
    private List<ListUser_Information> user_informations;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            ToolUtils.showToast(GeRen_Main_Activity.this, toastMsg);
        }
    };

    private PlatActionListener mPlatActionListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + (error != null ? error.getMessage() : "") + "---" + errorCode;
                Logger.dd("geren",message.obj+"");
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if(handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geren_main);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        uid = intent.getIntExtra("uid", 0);
        back = findViewById(R.id.back);
        rl_geren_main = findViewById(R.id.rl_geren_main);
        rl_geren_main_update_message = findViewById(R.id.rl_geren_main_update_message);
        rl_geren_main_fans = findViewById(R.id.rl_geren_main_fans);
        iv_geren_main_cover = findViewById(R.id.iv_geren_main_cover);
        iv_geren_main_header = findViewById(R.id.iv_geren_main_header);
        iv_geren_main_icon = findViewById(R.id.iv_geren_main_icon);
        ll_geren_main_ziliao = findViewById(R.id.ll_geren_main_ziliao);
        ll_geren_main_my_photo = findViewById(R.id.ll_geren_main_my_photo);
        ll_geren_main_tr_photo = findViewById(R.id.ll_geren_main_tr_photo);
        btn_gerentg_tgjl = findViewById(R.id.btn_gerentg_tgjl);
        btn_gerentg_ddjl = findViewById(R.id.btn_gerentg_ddjl);
        lv_geren_main_dongtai = findViewById(R.id.lv_geren_main_dongtai);
        tv_geren_main_name = findViewById(R.id.tv_geren_main_name);
        tv_geren_main_fans_count = findViewById(R.id.tv_geren_main_fans_count);
        tv_geren_main_age = findViewById(R.id.tv_geren_main_age);
        tv_geren_main_distance = findViewById(R.id.tv_geren_main_distance);
        tv_geren_main_gxqm = findViewById(R.id.tv_geren_main_gxqm);
        tv_geren_main_xingzuo = findViewById(R.id.tv_geren_main_xingzuo);
        iv_geren_main_is_vip = findViewById(R.id.iv_geren_main_is_vip);
        iv_geren_share = findViewById(R.id.iv_geren_share);
        tv_geren_main_mude = findViewById(R.id.tv_geren_main_mude);
        tv_geren_main_gqzk = findViewById(R.id.tv_geren_main_gqzk);
        tv_geren_main_guxiang = findViewById(R.id.tv_geren_main_guxiang);
        tv_geren_main_work = findViewById(R.id.tv_geren_main_work);
        tv_geren_main_sflb = findViewById(R.id.tv_geren_main_sflb);
        tv_geren_main_style = findViewById(R.id.tv_geren_main_style);
        tv_geren_main_tixing = findViewById(R.id.tv_geren_main_tixing);
        tv_geren_main_style2 = findViewById(R.id.tv_geren_main_style2);
        tv_taren_main_lock = findViewById(R.id.tv_taren_main_lock);
        fabtn_geren_main = findViewById(R.id.fabtn_geren_main);
        main_hlv = findViewById(R.id.main_hlv);
        back.setOnClickListener(this);
        rl_geren_main_update_message.setOnClickListener(this);
        btn_gerentg_tgjl.setOnClickListener(this);
        btn_gerentg_ddjl.setOnClickListener(this);
        iv_geren_main_cover.setOnClickListener(this);
        iv_geren_share.setOnClickListener(this);
        fabtn_geren_main.setOnClickListener(this);
        rl_geren_main_fans.setOnClickListener(this);
        ll_geren_main_my_photo.setOnClickListener(this);
        tv_taren_main_lock.setOnClickListener(this);
        rl_geren_main.bringChildToFront(iv_geren_main_icon);//显示在上层，不被遮挡
        rl_geren_main.updateViewLayout(iv_geren_main_icon, iv_geren_main_icon.getLayoutParams());
        postData();
        postTGData();
    }

    @SuppressLint({"RestrictedApi", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_geren_main_update_message:
                Intent intent = new Intent(this, GeRen_Update_Msg_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("user_limit", user_limit);
                startActivity(intent);
                break;
            case R.id.rl_geren_main_fans:
                Intent intent1 = new Intent(this, GeRen_Main_Fans_Activity.class);
                intent1.putExtra("access_token", access_token);
                intent1.putExtra("uid", user_limit.getUid());
                intent1.putExtra("fans", user_limit.getFans());
                intent1.putExtra("watch", user_limit.getWatch());
                intent1.putExtra("type", 1);
                intent1.putExtra("care", 1);
                startActivity(intent1);
                break;
            case R.id.btn_gerentg_tgjl:
                ll_geren_main_ziliao.setVisibility(View.GONE);
                lv_geren_main_dongtai.setVisibility(View.VISIBLE);
                fabtn_geren_main.setVisibility(View.VISIBLE);
                btn_gerentg_tgjl.setBackgroundResource(R.drawable.login_login);
                btn_gerentg_ddjl.setBackgroundResource(R.drawable.login_exit);
                postTGData();
                break;
            case R.id.btn_gerentg_ddjl:
                ll_geren_main_ziliao.setVisibility(View.VISIBLE);
                lv_geren_main_dongtai.setVisibility(View.GONE);
                fabtn_geren_main.setVisibility(View.GONE);
                btn_gerentg_tgjl.setBackgroundResource(R.drawable.login_exit);
                btn_gerentg_ddjl.setBackgroundResource(R.drawable.login_login);
                postData();
                break;
            case R.id.iv_geren_main_cover:
                Intent intent2 = new Intent(this, GeRen_Update_Msg_Cover_Activity.class);
                intent2.putExtra("access_token", access_token);
                startActivity(intent2);
                break;
            case R.id.fabtn_geren_main:
                fabtn_geren_main.setVisibility(View.GONE);
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_main_fabtn)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setOutsideTouchable(false)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsDown(v);
                break;
            case R.id.iv_geren_share:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_main_share)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsBottom(v);
                break;
            case R.id.ll_geren_main_my_photo:
                Intent intent3 = new Intent(this, GeRen_Update_Msg_PersonPhoto_Activity.class);
                intent3.putExtra("access_token", access_token);
                intent3.putExtra("user_limit", user_limit);
                startActivity(intent3);
                break;
            case R.id.tv_taren_main_lock:
                Intent intent4 = new Intent(this, GeRen_Update_Msg_PersonPhoto_Activity.class);
                intent4.putExtra("access_token", access_token);
                intent4.putExtra("user_limit", user_limit);
                startActivity(intent4);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    @SuppressLint("SetTextI18n")
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_user_information_xq_Url + access_token + "&uid=" + uid, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("geren_main", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        user_limit = gson.fromJson(info.toString(), User_Limit.class);
                        Glide.with(GeRen_Main_Activity.this).load(user_limit.getHead()).apply(new RequestOptions()
                                .placeholder(R.mipmap.fill_person_icon).error(R.mipmap.fill_person_icon)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                        ).into(iv_geren_main_header);
                        Glide.with(GeRen_Main_Activity.this).load(user_limit.getBackground()).apply(new RequestOptions()
                                .placeholder(R.mipmap.banner).error(R.mipmap.banner)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                        ).into(iv_geren_main_cover);
                        tv_geren_main_name.setText("" + user_limit.getNicename());
                        if (user_limit.getIs_vip() == 1){
                            tv_geren_main_name.setTextColor(Color.parseColor("#FF3B30"));
                            iv_geren_main_is_vip.setVisibility(View.VISIBLE);
                        } else {
                            tv_geren_main_name.setTextColor(Color.parseColor("#FFFFFF"));
                            iv_geren_main_is_vip.setVisibility(View.GONE);
                        }
                        tv_geren_main_fans_count.setText("" + user_limit.getFans());
                        tv_geren_main_age.setText("" + user_limit.getAge() + "/" + user_limit.getHeight() + "/" + user_limit.getWeigh() + "/" + user_limit.getType() + "/" + user_limit.getRole());
                        if (user_limit.getIs_online() == 0){
                            tv_geren_main_distance.setText("" + user_limit.getDistance() + "/离线");
                        } else {
                            tv_geren_main_distance.setText("" + user_limit.getDistance() + "/在线");
                        }
                        tv_geren_main_gxqm.setText("个性签名：" + user_limit.getRemark());
                        tv_geren_main_xingzuo.setText("" + user_limit.getConstellatory());
                        tv_geren_main_mude.setText("" + user_limit.getAim());
                        tv_geren_main_gqzk.setText("" + user_limit.getStatus());
                        tv_geren_main_guxiang.setText("" + user_limit.getProvince() + user_limit.getCity() + user_limit.getDistrict());
                        tv_geren_main_work.setText("" + user_limit.getWork());
                        tv_geren_main_sflb.setText("" + user_limit.getIdentity());
                        tv_geren_main_style.setText("" + user_limit.getStyle());
                        tv_geren_main_tixing.setText("" + user_limit.getI_face());
                        tv_geren_main_style2.setText("" + user_limit.getI_style());
                        JSONObject object = new JSONObject();
                        try {
                            object.put("uid", user_limit.getUid());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        postPhotoData(object);
                    } else {
                        ToolUtils.showToast(GeRen_Main_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Main_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postTGData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_my_dongtai_Url + access_token + "&page=1&limit=10&uid=" + uid, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("dongtai", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_informations = gson.fromJson(info.toString(), new TypeToken<List<ListUser_Information>>(){}.getType());
                        lv_geren_main_dongtai.setAdapter(new LV_DongtaiTG_Adapter(GeRen_Main_Activity.this, user_informations, 1, access_token));
                    } else {
                        ToolUtils.showToast(GeRen_Main_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Main_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postPhotoData(JSONObject object) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.tr_user_information_photo_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("dongtai", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        int is_support = info.getInt("is_support");
                        int photoStatus = info.getInt("photoStatus");
                        int photoHots = info.getInt("photoHots");
                        JSONArray files = info.getJSONArray("files");
                        List<ListUser_Information> user_informations = gson.fromJson(files.toString(), new TypeToken<List<ListUser_Information>>(){}.getType());
                        if (user_informations.size() > 0){
                            ll_geren_main_tr_photo.setVisibility(View.VISIBLE);
                            ll_geren_main_my_photo.setVisibility(View.GONE);
                        } else {
                            ll_geren_main_tr_photo.setVisibility(View.GONE);
                            ll_geren_main_my_photo.setVisibility(View.VISIBLE);
                        }
                        // 获取屏幕宽高
                        int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
                        TaRen_HorizontalListViewAdapter horizontalListViewAdapter = new TaRen_HorizontalListViewAdapter(GeRen_Main_Activity.this, screenWidth, user_informations, is_support);
                        main_hlv.setAdapter(horizontalListViewAdapter);
                        main_hlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            }
                        });
                    } else {
                        ToolUtils.showToast(GeRen_Main_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Main_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_main_fabtn:
                ImageView iv_geren_fabtn_guanbi = view.findViewById(R.id.iv_geren_fabtn_guanbi);
                ImageView iv_geren_fabtn_paishe = view.findViewById(R.id.iv_geren_fabtn_paishe);
                ImageView iv_geren_fabtn_xuanze = view.findViewById(R.id.iv_geren_fabtn_xuanze);
                iv_geren_fabtn_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        fabtn_geren_main.setVisibility(View.VISIBLE);
                    }
                });
                iv_geren_fabtn_paishe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            //只是加了一个uri作为地址传入
                            Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            try {
                                File photoFile = createImgFile();
                                photoUri = Uri.fromFile(photoFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            cropPhoto(photoUri);
                            intent2.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);//指定了存储的路径的uri，那么返回的data就为null
                            startActivityForResult(intent2, TAKE_PHOTO);
                        } else {
                            ToolUtils.showToast(GeRen_Main_Activity.this, "SD卡不可用~");
                        }
                    }
                });
                iv_geren_fabtn_xuanze.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        Intent intent = new Intent(GeRen_Main_Activity.this, PhotoAlbum_Activity.class);
                        intent.putExtra("access_token", access_token);
                        intent.putExtra("bucket", "photo");
                        intent.putExtra("cos_type", 1);
                        startActivity(intent);
                    }
                });
                break;
            case R.layout.pop_geren_main_share:
                List<String> platformList = JShareInterface.getPlatformList();
                if (platformList == null || platformList.isEmpty()) {
                    ToolUtils.showToast(this, "请检查配置文件是否正确");
                    finish();
                    return;
                }
                ShareParams shareParams = new ShareParams();
                shareParams.setUrl("https://www.jiguang.cn");
                shareParams.setTargetPkg("com.tencent.mm");
                shareParams.setTargetClass("com.tencent.mm.ui.LauncherUI");
                shareParams.setExtra("this message from jshare.");
                LinearLayout ll_pop_cancel = view.findViewById(R.id.ll_pop_cancel);
                LinearLayout ll_pop_geren_haoyou = view.findViewById(R.id.ll_pop_geren_haoyou);
                LinearLayout ll_pop_geren_wx = view.findViewById(R.id.ll_pop_geren_wx);
                LinearLayout ll_pop_geren_pyq = view.findViewById(R.id.ll_pop_geren_pyq);
                LinearLayout ll_pop_geren_qq = view.findViewById(R.id.ll_pop_geren_qq);
                LinearLayout ll_pop_geren_wb = view.findViewById(R.id.ll_pop_geren_wb);
                ll_pop_geren_wx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有微信支持表情
                        shareParams.setShareType(Platform.SHARE_EMOJI);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        shareParams.setFilePath(MyApplication.ImagePath);
                        //只有微信支持文件
                        shareParams.setShareType(Platform.SHARE_FILE);
                        shareParams.setFilePath(MyApplication.ImagePath);
                        //只有微信支持小程序分享
//                        shareParams.setShareType(Platform.SHARE_MINI_PROGRAM);
//                        shareParams.setTitle("极光分享");
//                        shareParams.setText("分享");
//                        shareParams.setUrl("https://www.jiguang.cn");
//                        shareParams.setImagePath(MyApplication.ImagePath);
//                        shareParams.setMiniProgramWithShareTicket(false);//可以设置withShareTicket为true，当分享卡片在群聊中被其他用户打开时，可以获取到shareTicket
//                        shareParams.setMiniProgramType(0);// 正式版:0，开发版（测试版）:1，体验版（预览版）:2
//                        shareParams.setMiniProgramImagePath(MyApplication.ImagePath);//小程序图片地址
//                        shareParams.setMiniProgramPath("pages/index/index");//小程序页面路径
//                        shareParams.setMiniProgramUserName("gh_cd370c00d3d4");//小程序原始id·
                        JShareInterface.share(Wechat.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_geren_pyq.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有微信支持文件
                        shareParams.setShareType(Platform.SHARE_FILE);
                        JShareInterface.share(WechatMoments.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_geren_qq.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //只有支持QQ APP
                        shareParams.setShareType(Platform.SHARE_APPS);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        JShareInterface.share(QQ.Name, shareParams, mPlatActionListener);
//                        JShareInterface.share(QZone.Name, shareParams, mPlatActionListener);//QQ空间
                    }
                });
                ll_pop_geren_wb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shareParams.setTitle("极光分享");
                        shareParams.setText("分享");
                        shareParams.setUrl("https://www.jiguang.cn");
                        shareParams.setShareType(Platform.SHARE_WEBPAGE);
                        shareParams.setImagePath(MyApplication.ImagePath);
                        JShareInterface.share(SinaWeiboMessage.Name, shareParams, mPlatActionListener);
                    }
                });
                ll_pop_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
//                shareParams.setShareType(Platform.SHARE_IMAGE);
//                shareParams.setImageUrl("");
//                JShareInterface.share("", shareParams, mPlatActionListener);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        postData();
    }

    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() throws IOException {
        //创建文件
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";//确定文件名
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = getExternalCacheDir();
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir.getPath(), fileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
        //获取文件路径
        currentUploadPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    //将图片添加进手机相册
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(photoUri);
        this.sendBroadcast(mediaScanIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    galleryAddPic();
                    break;
                case RESULT_REQUEST_CODE:
                    Log.d("fill", "111" + currentUploadPath);
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap head = extras.getParcelable("data");
//                        Bitmap bitmap = BitmapFactory.decodeFile(currentUploadPath);
//                            iv_fill_information_icon.setImageBitmap(bitmap);
                        if (head != null) {
//                                iv_fill_information_icon.setImageBitmap(head);//按钮加载图片
                            ImageUtils.bitmapToBase64(head);//base64加密
                            try {
                                ImageUtils.saveBitmapToFile(head, currentUploadPath);
//                                    upload();
                                new PhotoAlbum_Activity().upload(currentUploadPath, "head", access_token, GeRen_Main_Activity.this, 1);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler != null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
